#include "IO.h"
#include "buffer.h"
#include "shm.h"
#include "ipc.h"



// 新增函数：将格式化字符串写入缓冲区
void Log(int pid, const char* string, int time, int isP) {
    char formattedString[STRING_LENGTH];
    if (isP) {
        snprintf(formattedString, sizeof(formattedString), "[%ld] Process %d: %s\n", (long)time, pid, string);
    } else {
        snprintf(formattedString, sizeof(formattedString), "[%ld] Job %d: %s\n", (long)time, pid, string);
    }
    while(buffer->count==BUFFER_SIZE){
        printf("getlocked\n");
        Sleep(2000);
    }

    sem_wait(Semid);
    if (buffer->count < BUFFER_SIZE) {
        strcpy(buffer->strings[buffer->in], formattedString);
        buffer->in = (buffer->in + 1) % BUFFER_SIZE;
        buffer->count++;
        //printf("%d %d\n",buffer->count,BUFFER_SIZE);
    }
    sem_post(Semid);
}


// 新增函数：将错误信息写入缓冲区
void LogErr( const char* string, int time) {
    char formattedString[STRING_LENGTH];

    snprintf(formattedString, sizeof(formattedString), "[%ld] Error: %s\n", time, string);
    while(buffer->count==BUFFER_SIZE){
        printf("getlocked\n");
        Sleep(2000);
    }
    sem_wait(Semid);
    if (buffer->count < BUFFER_SIZE) {
        strcpy(buffer->strings[buffer->in], formattedString);
        buffer->in = (buffer->in + 1) % BUFFER_SIZE;
        buffer->count++;
    }
    printf("%s\n",formattedString);
    sem_post(Semid);
}

